import 'package:flutter/material.dart';
import 'package:like_chat/blocs/message_list_bloc.dart';
import 'package:like_chat/entity/Messages.dart';
import 'package:like_chat/entity/user.dart';
import 'package:like_chat/final_values.dart';

class MessageListWidget extends StatefulWidget {

  final MessageListBloc bloc;

  final User user;

  MessageListWidget(this.bloc, this.user);

  @override
  _MessageListWidgetState createState() => _MessageListWidgetState();
}

class _MessageListWidgetState extends State<MessageListWidget> {

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Container(
        color: Color(backgroundColorValue),
        child: StreamBuilder<List<Messages>>(
          builder: (context, snapshot) {
            return NotificationListener(
              onNotification: _callback,
              child: ListView.builder(
                reverse: true,
                itemBuilder: (context, index) =>
                    _itemBuilder(context, snapshot.data[index]),
                itemCount: snapshot.data.length,
              ),
            );
          },
          stream: widget.bloc.outMessagesStream,
          initialData: [],
        ),
      ),
    );
  }

  Widget _itemBuilder(BuildContext context, Messages m) {
    return ListTile(
      title: Text(m.toString()),
    );
  }

  bool _callback(Notification notification) {
    if (notification is ScrollEndNotification) {
      //下滑到最底部
      if (notification.metrics.extentAfter == 0.0) {
        print('======下滑到最底部======');
        widget.bloc.addLastMessage(Messages(mid:
        DateTime.now().millisecondsSinceEpoch.toString()));
      }
      //滑动到最顶部
      if (notification.metrics.extentBefore == 0.0) {
        print('======滑动到最顶部======');
      }
    }
    return true;
  }
}

